package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConst;
import com.itheima.entity.Result;
import com.itheima.exception.BusinessRuntimeException;
import com.itheima.service.MemberService;
import com.itheima.service.ReportService;
import com.itheima.service.SetmealService;
import com.itheima.utils.DateUtils;
import com.itheima.utils.POIUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * @author 黑马程序员
 * @Company http://www.ithiema.com
 * @Version 1.0
 */
@RestController
@RequestMapping("/report")
@Slf4j
public class ReportController {

    @Reference
    MemberService memberService;

    @Reference
    SetmealService setmealService;

    @Reference
    ReportService reportService;


    @RequestMapping("/getBusinessReportData")
    public Result getBusinessReportData(){
        log.debug("运营数据统计！！");
        Map<String,Object> result = reportService.getBussinessReport();
        log.debug("result:"+result);
        return new Result(true,MessageConst.ACTION_SUCCESS, result );
    }

    @RequestMapping("/getMemberReport")
    public Result getMemberReport(){
        log.debug("getMemberReport: 获取会员统计信息");
        Map<String,Object> map = memberService.getMemberReport();
        log.debug("MemberReport: " + map );
        log.debug("获取会员统计信息成功!!");
        return new Result(true, MessageConst.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);
    }

    @RequestMapping("/getMemberReportt")
    public Result getMemberReportt() {
        try {
            // 计算出月份
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.MONTH, -11);
            //组装月份数据
            List<String> month_param = new ArrayList<String>(12);
            List<String> months = new ArrayList<String>(12);
            for (int i = 0; i < 12; i++) {
                Date date01 = calendar.getTime();
                months.add(DateUtils.getStringByDate(date01, "yyyy-MM"));
                calendar.add(Calendar.MONTH, 1);
                Date date = calendar.getTime();
                String month = DateUtils.getStringByDate(date, "yyyy-MM");
                month_param.add(month);
            }
            //查询会员数量
            List<Integer> memberCounts = memberService.findCountByMonths(month_param);
            Map<String, Object> map = new HashMap<String, Object>(2);
            map.put("months", months);
            map.put("memberCounts", memberCounts);
            return new Result(true, MessageConst.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConst.GET_MEMBER_NUMBER_REPORT_FAIL);
        }
    }


    @RequestMapping("/getSetmealReport")
    public Result getSetmealReport(){
        log.debug("ReportController-getSetmealReport: 获取套餐统计信息");
        List<String> setmealNames = new ArrayList<>();//封装套餐名称集合
        List<Map> setmealCount = setmealService.getSetmealReport();//套餐名称和预约数量集合
        if(setmealCount != null && setmealCount.size() > 0){
            for (Map map : setmealCount) {
                String name = (String) map.get("name");//套餐名称
                setmealNames.add(name);
            }
        }
        Map<String,Object> map = new HashMap<>();
        map.put("setmealNames",setmealNames);
        map.put("setmealCount",setmealCount);
        log.debug("getSetmealReport:" + map.toString());
        return new Result(true, MessageConst.GET_SETMEAL_COUNT_REPORT_SUCCESS,map);
    }

    /**
     * 1. 获取运营统计数据
     * 2. 创建模板对象
     * 3. 把数据写入模板中
     * 4. 下载excel到本地
     */
    @RequestMapping("/exportBusinessReport")
    public void exportBusinessReport(HttpServletResponse response) {
        try {

//1. 获取运营统计数据
            Map<String, Object> businessReportData = reportService.getBussinessReport();
            //获取统计日期
            Object reportDate = businessReportData.get("reportDate");
            Object totalMember = businessReportData.get("totalMember");
            Object todayNewMember = businessReportData.get("todayNewMember");
            Object thisWeekNewMember = businessReportData.get("thisWeekNewMember");
            Object thisMonthNewMember = businessReportData.get("thisMonthNewMember");
            Object todayOrderNumber = businessReportData.get("todayOrderNumber");
            Object todayVisitsNumber = businessReportData.get("todayVisitsNumber");
            Object thisWeekOrderNumber = businessReportData.get("thisWeekOrderNumber");
            Object thisWeekVisitsNumber = businessReportData.get("thisWeekVisitsNumber");
            Object thisMonthOrderNumber = businessReportData.get("thisMonthOrderNumber");
            Object thisMonthVisitsNumber = businessReportData.get("thisMonthVisitsNumber");
            List<Map<String, Object>> hotSetmeal = (List<Map<String, Object>>) businessReportData.get("hotSetmeal");

            //创建模板对象
            InputStream inputStream = this.getClass().getResourceAsStream("/template/report_template.xlsx");
            XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
            //把数据写入模板中
            //获取工作表对象（sheet）
            XSSFSheet sheet = workbook.getSheet("Sheet1");
            //设置统计日期
            //获取行对象
            POIUtils.writeCell(sheet, 2, 5, reportDate);

            //设置今日新增会员数
            POIUtils.writeCell(sheet, 4, 5, todayNewMember);

            //设置总会员数
            POIUtils.writeCell(sheet, 4, 7, totalMember);

            //设置本周新增会员数
            POIUtils.writeCell(sheet, 5, 5, thisWeekNewMember);

            //设置本月新增会员数
            POIUtils.writeCell(sheet, 5, 7, thisMonthNewMember);


            //设置今日预约数
            POIUtils.writeCell(sheet, 7, 5, todayOrderNumber);

            //设置今日到诊数
            POIUtils.writeCell(sheet, 7, 7, todayVisitsNumber);

            //设置本周预约数
            POIUtils.writeCell(sheet, 8, 5, thisWeekOrderNumber);

            //设置本周到诊数
            POIUtils.writeCell(sheet, 8, 7, thisWeekVisitsNumber);

            //设置本月预约数
            POIUtils.writeCell(sheet, 9, 5, thisMonthOrderNumber);


            //设置本月到诊数
            POIUtils.writeCell(sheet, 9, 7, thisMonthVisitsNumber);

            //声明行号
            int rownum = 12;
            for (Map<String, Object> map : hotSetmeal) {
                POIUtils.writeCell(sheet, rownum, 4, map.get("name"));
                POIUtils.writeCell(sheet, rownum, 5, map.get("setmeal_count"));
                POIUtils.writeCell(sheet, rownum, 6, map.get("proportion"));

                rownum++;
            }
            //下载excel到本地
            // 通过输出流进行文件下载
            ServletOutputStream out = response.getOutputStream();
            //指定附件的格式为excel
            response.setContentType("application/vnd.ms-excel");
            //attachment 以附件下载
            //下载弹出框架中的默认的文件名
            response.setHeader("content-Disposition", "attachment;filename=" + reportDate + "_report.xlsx");
            //输出流下载
            workbook.write(out);
            out.flush();
            out.close();
            workbook.close();

        } catch (IOException e) {
            e.printStackTrace();
            throw new BusinessRuntimeException(MessageConst.GET_BUSINESS_REPORT_FAIL);
        }
    }
    @RequestMapping("/getMemberReportBetweenDays")
    public Result getMemberReportBetweenDays(String start, String end) {
        try {
            Date date01 = DateUtils.getDateByString(start, "yyyy-MM-dd");
            Date date02 = DateUtils.getDateByString(end, "yyyy-MM-dd");
            List<String> months = new ArrayList<String>();
            List<String> months_param = new ArrayList<String>();
            while (date01.getTime() <= date02.getTime()) {
                months.add(DateUtils.getStringByDate(date01, "yyyy-MM"));
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(date01);
                calendar.add(Calendar.MONTH, 1);
                Date date = calendar.getTime();
                months_param.add(DateUtils.getStringByDate(date, "yyyy-MM"));
                date01 = date;
            }
            List<Integer> memberCounts = memberService.findCountByMonths(months_param);
            Map<String, Object> map = new HashMap<String, Object>(2);
            map.put("months", months);
            map.put("memberCounts", memberCounts);

//            memberService.
            return new Result(true, MessageConst.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConst.GET_MEMBER_NUMBER_REPORT_FAIL);
        }
    }
    @RequestMapping("/getMemberSexReport")
    public Result getMemberSexReport(){
        try {
            List<Map<String,Object>> setmealCount = memberService.getMemberSexReport();
            List<Object> setmealNames = new ArrayList<>();
            //抽取map集合中name属性值
            for (Map<String, Object> map : setmealCount) {
                Object name = map.get("name");
                setmealNames.add(name);
            }
            //创建返回数据map
            Map<String,Object> map = new HashMap<>();
            map.put("setmealNames",setmealNames );
            map.put("setmealCount", setmealCount);
            return new Result(true,MessageConst.GET_SETMEAL_COUNT_REPORT_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConst.GET_SETMEAL_COUNT_REPORT_FAIL);
        }
    }
    /**
     * 展示各个年龄段的占比
     * @return
     */
    @RequestMapping("/getMemberAgeReport")
    public Result getMemberAgeReport(){
        try {
            List<Map<String,Object>> setmealCount = memberService.getMemberAgeReport();
            List<Object> setmealNames = new ArrayList<>();
            //抽取map集合中name属性值
            for (Map<String, Object> map : setmealCount) {
                Object name = map.get("name");
                setmealNames.add(name);
            }
            //创建返回数据map
            Map<String,Object> map = new HashMap<>();
            map.put("setmealNames",setmealNames );
            map.put("setmealCount", setmealCount);
            return new Result(true,MessageConst.GET_SETMEAL_COUNT_REPORT_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConst.GET_SETMEAL_COUNT_REPORT_FAIL);
        }
    }

    @RequestMapping("/handleApp")
    public Result handleApp(@RequestBody String[] dates) {
        try {
            List<String> list = new ArrayList<>();
            for (String date : dates) {
//                SimpleDateFormat str = new SimpleDateFormat("yyyy-MM-dd");
//                String dateStr = str.format(date);
                //String dateStr = DateUtils.parseDate2String(date);
                String substring = date.substring(0, date.lastIndexOf("-"));
                String[] split = substring.split("-");
                int parseInt = Integer.parseInt(split[1]);
                parseInt++;
                String substring1 = split[0] + "-" + parseInt;
                System.out.println("===================================================" + substring);
                list.add(substring1);
            }
            //获取两个时间段中的月份
            List<String> monthList = DateUtils.getMonthBetween(list.get(0), list.get(1), "yyyy-MM");
            System.out.println(monthList);
            //根据月份获取每月的会员数量
            List<Integer> memberCount = memberService.findCountByMonths(monthList);
            Map<String, Object> map = new HashMap<>();
            map.put("monthList", monthList);
            map.put("memberCount", memberCount);
            return new Result(true, MessageConst.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConst.GET_MEMBER_NUMBER_REPORT_FAIL);
        }
    }

}
